package com.aigou.admin.service.impl;

import com.aigou.admin.dao.UserDAO;
import com.aigou.admin.dao.impl.UserDAOImpl;
import com.aigou.admin.entity.PageEntity;
import com.aigou.admin.entity.User;
import com.aigou.admin.service.UserService;
import com.aigou.admin.util.MD5Utils;

import java.util.List;

/**
 * 业务逻辑实现类
 */
public class UserServiceImpl implements UserService {

    //调用dao层对象
    private UserDAO userDAO = new UserDAOImpl();

    @Override
    public PageEntity<User> findUserPage(Integer current, Integer pageSize) {
        //查询用户总数 count(*)
        int total = userDAO.selectUserCount();
        //分页查询用户数据 limit
        List<User> users = userDAO.selectUserLimit((current - 1) * pageSize, pageSize);
        //包装数据发送给前端
        PageEntity<User> pageEntity = new PageEntity<>();
        pageEntity.setCurrent(current);
        pageEntity.setPageSize(pageSize);
        pageEntity.setTotal(total);
        pageEntity.setRecords(users);
        return pageEntity;
    }

    /**
     * 登录业务逻辑
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        //按用户名查询用户
        User user = userDAO.selectByUsername(username);
        if(user == null){
            return null;
        }
        //用户存在再判断密码，将用户填写的密码加密后，和数据库密码比较
        String pass = MD5Utils.md5(password);
        //相同就返回用户
        if(pass.equals(user.getUser_pwd())){
            return user;
        }
        return null;
    }

    @Override
    public List<User> findAll() {
        return userDAO.selectAll();
    }

    @Override
    public User findById(String userId) {
        return userDAO.selectById(userId);
    }

    @Override
    public boolean save(User user) {
        user.setUser_pwd(MD5Utils.md5(user.getUser_pwd()));
        return userDAO.insert(user);
    }

    @Override
    public boolean remove(String userId) {
        return userDAO.delete(userId);
    }

    @Override
    public boolean update(User user) {
        user.setUser_pwd(MD5Utils.md5(user.getUser_pwd()));
        return userDAO.update(user);
    }
}
